var canvas = document.getElementById('canvas'),
    context = canvas.getContext('2d'),
    repeatRadio = document.getElementById('repeatRadio'),
    noRepeatRadio = document.getElementById('noRepeatRadio'),
    repeatXRadio = document.getElementById('repeatXRadio'),
    repeatYRadio = document.getElementById('repeatYRadio'),
    image = new Image();

function fillCanvasWithPattern(repeatString) {
    /**
     * createPattern() 方法在指定的方向内重复指定的元素。
     元素可以是图片、视频，或者其他 <canvas> 元素。
     被重复的元素可用于绘制/填充矩形、圆形或线条等等。
     * @type {CanvasPattern}
     */
    var pattern = context.createPattern(image, repeatString);
    context.clearRect(0, 0, canvas.width, canvas.height);//清除当前画布
    context.fillStyle = pattern;//设置填充样式
    context.fillRect(0, 0, canvas.width, canvas.height);//填充画布
    context.fill();//填充
};
/**
 * 下面几个方法都是各种点击事件了 很简单吧
 * @param e
 */
repeatRadio.onclick = function (e) {
    fillCanvasWithPattern('repeat');
};

repeatXRadio.onclick = function (e) {
    fillCanvasWithPattern('repeat-x');
};

repeatYRadio.onclick = function (e) {
    fillCanvasWithPattern('repeat-y');
};

noRepeatRadio.onclick = function (e) {
    fillCanvasWithPattern('no-repeat');
};

image.src = 'redball.png';
image.onload = function (e) {
    fillCanvasWithPattern('repeat');
};

